/*
 * Copyright (c) 2007
 *	Alberto Magni, Maggioni Marcello
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

package Database.XMLManager;

import exceptions.DatabaseException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 *  This class the representation of a Address information storing file in XML format
 * 
 * @author Marcello Maggioni
 */
public class XMLAddressFile extends XMLFile {

    /**
     * Constructs an instance of XMLAddressFile
     * 
     * @param path The path of the XML file
     * @throws javax.xml.parsers.ParserConfigurationException
     * @throws javax.xml.transform.TransformerConfigurationException
     * @throws exceptions.DatabaseException
     */
    protected XMLAddressFile(String path) throws ParserConfigurationException, TransformerConfigurationException, DatabaseException {
        super(path);
        if (!exists()) {
            init();
        }
    }

    /**
     * Get the addresses stored in the file
     * @return the addresses stored
     * @throws exceptions.DatabaseException
     */
    protected String[] getAddresses() throws DatabaseException {
        Document doc = readFile();
        Element root = doc.getDocumentElement();
        ArrayList<String> addresses = new ArrayList<String>();
        NodeList nl = root.getElementsByTagName("address");
        for (int count = 0; count < nl.getLength(); count++) {
            addresses.add(nl.item(count).getTextContent());
        }

        return addresses.toArray(new String[0]);
    }
    /**
     * Set the addresses stored in the file
     * @param addresses An array of strings containing the addresses
     * @param original_filename The filename of the original file. If the file doesn't come from a conversion from another file set this to null or empty string
     * @throws exceptions.DatabaseException
     */
    protected void setAddresses(String[] addresses, String original_filename) throws DatabaseException {
        init();
        Document doc = readFile();
        Element root = doc.getDocumentElement();
        if (original_filename != null && !original_filename.isEmpty())
            root.setAttribute("origfilename", original_filename);
        for (String addr : addresses) {
            Element address = doc.createElement("address");
            address.setTextContent(addr);
            root.appendChild(address);
        }
        writeFile(doc);
    }

    protected String getOriginalFilename() throws DatabaseException {
        Document doc = readFile();
        Element root = doc.getDocumentElement();
        String origfilename = root.getAttribute("origfilename");
        if (origfilename == null || origfilename.isEmpty())
            return null;
        return origfilename;
    }
    
    @Override
    protected InputStream getInputStream() throws DatabaseException {
        return super.getInputStream();
    }

    private void init() throws DatabaseException {
        try {
            super.initialize();
            Document d = readFile();
            Element messages = d.createElement("addresses");
            d.appendChild(messages);
            writeFile(d);
        } catch (Exception ex) {
            throw new DatabaseException(ex.getMessage());
        }
    }
}
